package org.jeecg.modules.common.security.plugin;

import org.apache.commons.collections4.MapUtils;
import org.jeecg.modules.common.security.visitor.SecurityExpressionVisitor;
import org.jeecg.modules.common.sensitive.entity.SensitiveRule;

import java.util.Optional;
import java.util.function.Function;

/**
 * @author xufeixiang
 * @Description TODO
 * @date 2022年06月11日 09:57
 */
public class SensitivePlugin extends AbstractSecurityPlugin {

    @Override
    public SecurityMethodConfig getSelectConfig() {
        return super.simpleSelect();
    }

    @Override
    public Function<SecurityExpressionVisitor.ColumnExpression, String> getColumnExpressionFunction() {
        return columnExpression -> {
            SensitiveRule sensitiveRule = super.getSensitiveRule(columnExpression.getColumnConfig().getSensitiveRuleId());
            return Optional.ofNullable(sensitiveRule.getPluginJsonParam())
                    .map(jsonParam -> {
                        int start = MapUtils.getIntValue(jsonParam, "start") - 1;
                        int end = MapUtils.getIntValue(jsonParam, "end");
                        String columnWithTableAlias = columnExpression.getColumnWithTableAlias();
                        String sensitiveFormat = "CONCAT(LEFT(%s,%s),REPEAT('*',%s),RIGHT(%s,LENGTH(%s) - %s))";
                        return String.format(sensitiveFormat,
                                columnWithTableAlias, start, // LEFT(%s,%s)
                                end - start, // REPEAT('*',%s)
                                columnWithTableAlias, columnWithTableAlias, end // RIGHT(%s,LENGTH(%s) - %s)
                        );
                    }).orElse(null);
        };
    }
}
